import { getPool } from '../database/db.js';
import { log } from '../utils/logger.js';
import { encrypt, decrypt } from '../utils/crypto.js';

export class Server {
  /**
   * 创建服务器配置
   */
  static async create(userId, serverData) {
    const pool = getPool();
    try {
      const { 
        name, host, port = 22, username, authType = 'password', 
        password, privateKey, groupName = 'default', expireDate = null 
      } = serverData;

      // 加密敏感信息
      const encryptedPassword = password ? encrypt(password) : null;
      const encryptedPrivateKey = privateKey ? encrypt(privateKey) : null;
      
      // 处理日期格式：MySQL DATE类型只需要 YYYY-MM-DD
      const formattedExpireDate = expireDate ? expireDate.split('T')[0] : null;

      const [result] = await pool.execute(
        `INSERT INTO servers (user_id, name, host, port, username, auth_type, password, private_key, group_name, expire_date)
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
        [userId, name, host, port, username, authType, encryptedPassword, encryptedPrivateKey, groupName, formattedExpireDate]
      );

      log.system(`服务器配置创建成功: ${name}`, { userId, serverId: result.insertId });
      return result.insertId;
    } catch (error) {
      log.error('服务器配置创建失败', { error: error.message, userId });
      throw error;
    }
  }

  /**
   * 获取用户的所有服务器
   */
  static async getAllByUser(userId) {
    const pool = getPool();
    try {
      const [rows] = await pool.execute(
        `SELECT id, name, host, port, username, auth_type, group_name, sort_order, expire_date, created_at, updated_at
         FROM servers 
         WHERE user_id = ?
         ORDER BY group_name, sort_order, name`,
        [userId]
      );
      return rows;
    } catch (error) {
      log.error('获取服务器列表失败', { error: error.message, userId });
      throw error;
    }
  }

  /**
   * 根据ID获取服务器（包含解密的凭证）
   */
  static async getById(id, userId) {
    const pool = getPool();
    try {
      const [rows] = await pool.execute(
        'SELECT * FROM servers WHERE id = ? AND user_id = ?',
        [id, userId]
      );
      
      const server = rows[0] || null;

      if (server) {
        console.log('🔍 服务器原始数据:', {
          id: server.id,
          name: server.name,
          auth_type: server.auth_type,
          has_password: !!server.password,
          has_private_key: !!server.private_key
        });
        
        // 解密敏感信息
        if (server.password) {
          try {
            server.password = decrypt(server.password);
            console.log('✅ 密码解密成功');
          } catch (err) {
            console.error('❌ 密码解密失败:', err.message);
            server.password = null;
          }
        }
        if (server.private_key) {
          try {
            server.private_key = decrypt(server.private_key);
            console.log('✅ 私钥解密成功');
          } catch (err) {
            console.error('❌ 私钥解密失败:', err.message);
            server.private_key = null;
          }
        }
        
        console.log('🔍 解密后:', {
          has_password: !!server.password,
          has_private_key: !!server.private_key
        });
      }

      return server;
    } catch (error) {
      log.error('获取服务器配置失败', { error: error.message, serverId: id, userId });
      throw error;
    }
  }

  /**
   * 更新服务器配置
   */
  static async update(id, userId, updates) {
    const pool = getPool();
    try {
      const allowedFields = ['name', 'host', 'port', 'username', 'auth_type', 'password', 'private_key', 'group_name', 'sort_order', 'expire_date'];
      const fields = [];
      const values = [];

      for (const [key, value] of Object.entries(updates)) {
        if (allowedFields.includes(key)) {
          // 跳过 undefined 值，但允许 null（用于清除字段）
          if (value === undefined) continue;
          
          // 加密敏感字段
          if (key === 'password' && value) {
            fields.push(`${key} = ?`);
            values.push(encrypt(value));
          } else if (key === 'private_key' && value) {
            fields.push(`${key} = ?`);
            values.push(encrypt(value));
          } else if (key === 'expire_date' && value) {
            // 处理日期格式：将ISO格式转换为MySQL DATE格式
            fields.push(`${key} = ?`);
            const dateOnly = value.split('T')[0]; // 只取日期部分 YYYY-MM-DD
            values.push(dateOnly);
          } else {
            fields.push(`${key} = ?`);
            values.push(value);
          }
        }
      }

      if (fields.length === 0) {
        return false;
      }

      values.push(id, userId);
      await pool.execute(
        `UPDATE servers SET ${fields.join(', ')} WHERE id = ? AND user_id = ?`,
        values
      );

      log.system('服务器配置更新成功', { serverId: id, userId });
      return true;
    } catch (error) {
      console.error('❌ Server.update 错误详情:', error);
      log.error('服务器配置更新失败', { 
        error: error.message, 
        code: error.code,
        sql: error.sql,
        serverId: id, 
        userId,
        updates: JSON.stringify(updates)
      });
      throw error;
    }
  }

  /**
   * 删除服务器配置
   */
  static async delete(id, userId) {
    const pool = getPool();
    try {
      const [result] = await pool.execute(
        'DELETE FROM servers WHERE id = ? AND user_id = ?',
        [id, userId]
      );
      
      if (result.affectedRows > 0) {
        log.system('服务器配置删除成功', { serverId: id, userId });
        return true;
      }
      
      return false;
    } catch (error) {
      log.error('服务器配置删除失败', { error: error.message, serverId: id, userId });
      throw error;
    }
  }

  /**
   * 获取服务器数量
   */
  static async getCountByUser(userId) {
    const pool = getPool();
    try {
      const [rows] = await pool.execute(
        'SELECT COUNT(*) as count FROM servers WHERE user_id = ?',
        [userId]
      );
      return rows[0].count;
    } catch (error) {
      log.error('获取服务器数量失败', { error: error.message, userId });
      throw error;
    }
  }

  /**
   * 根据分组获取服务器
   */
  static async getByGroup(userId, groupName) {
    const pool = getPool();
    try {
      const [rows] = await pool.execute(
        `SELECT id, name, host, port, username, auth_type, group_name, sort_order, expire_date, created_at
         FROM servers 
         WHERE user_id = ? AND group_name = ?
         ORDER BY sort_order, name`,
        [userId, groupName]
      );
      return rows;
    } catch (error) {
      log.error('获取分组服务器失败', { error: error.message, userId, groupName });
      throw error;
    }
  }

  /**
   * 获取所有分组
   */
  static async getGroups(userId) {
    const pool = getPool();
    try {
      const [rows] = await pool.execute(
        'SELECT DISTINCT group_name FROM servers WHERE user_id = ? ORDER BY group_name',
        [userId]
      );
      return rows.map(row => row.group_name);
    } catch (error) {
      log.error('获取服务器分组失败', { error: error.message, userId });
      throw error;
    }
  }
}
